/**
 * Copyright 2007-2010 非也
 * All rights reserved. 
 * 
 * This library is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License v3 as published by the Free Software
 * Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with this library; if not, see http://www.gnu.org/licenses/lgpl.html.
 *
 */
package org.fireflow2.designer.eclipse.properties.activity;

import java.util.List;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.views.properties.tabbed.AbstractPropertySection;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
import org.fireflow.model.binding.ResourceBinding;
import org.fireflow.model.binding.impl.ResourceBindingImpl;
import org.fireflow.model.resourcedef.ResourceDef;
import org.fireflow.pdl.fpdl20.process.Activity;
import org.fireflow.pdl.fpdl20.process.WorkflowProcess;
import org.fireflow2.designer.eclipse.Activator;
import org.fireflow2.designer.eclipse.commands.resourcedef.CreateResourceDefCommand;
import org.fireflow2.designer.eclipse.modelwrapper.ModelWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.SubProcessWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.WorkflowProcessWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.Wrapper;
import org.fireflow2.designer.eclipse.modelwrapper.basic.ActivityWrapper;
import org.fireflow2.designer.eclipse.modelwrapper.basic.ResourceDefWrapper;
import org.fireflow2.designer.eclipse.parts.basic.BasicActivityPart;
import org.fireflow2.designer.eclipse.util.Util4Eclipse;

/**
 *
 * @author 非也 nychen2000@163.com
 * Fire Workflow 官方网站：www.firesoa.com 或者 www.fireflow.org
 *
 */
public class ResourceBindingPropertySection  extends AbstractPropertySection {
	private Image newResourceImage = null;
	private Image deleteImage = null;
	private Image addImage = null;
	
	public ResourceBindingPropertySection(){
		ImageDescriptor imageDescriptor = ImageDescriptor.createFromFile(Activator.class, "resources/new_resource.png");
		newResourceImage = imageDescriptor.createImage();
		imageDescriptor = ImageDescriptor.createFromFile(Activator.class, "resources/delete.png");
		deleteImage = imageDescriptor.createImage();
		
		imageDescriptor = ImageDescriptor.createFromFile(Activator.class, "resources/add.png");
		addImage = imageDescriptor.createImage();
	}

	ActivityWrapper activityWrapper = null;
	BasicActivityPart activityPart = null;
	ResourceBinding resourceBinding = null;
	WorkflowProcessWrapper processWrapper = null;
	
	TableViewer potentialOwnerTableViewer = null;
	
	public void createControls(Composite parent,
			TabbedPropertySheetPage aTabbedPropertySheetPage) {
		super.createControls(parent, aTabbedPropertySheetPage);

		parent.setLayout(new GridLayout(1,false));	
		Composite composite = parent;

		final CTabFolder tabFolder = new CTabFolder(composite, SWT.NONE
				| SWT.BORDER);

		GridData gridData = new GridData(GridData.FILL_BOTH); 
		gridData.heightHint = 150;
		tabFolder.setLayoutData(gridData);
		
		// 下面是设置渐变色
		// Color[] color=new Color[4];
		// color[0]= ColorConstants.darkBlue;
		// color[1]= ColorConstants.blue;
		// color[2]= ColorConstants.darkGray;
		// color[3]= ColorConstants.white;
		// int[] intArray=new int[]{25,45,100};
		// tabFolder.setSelectionBackground(color, intArray);
		tabFolder.setSimple(false);// 设置圆角
		// tabFolder.setUnselectedCloseVisible(true);
		tabFolder.setSelectionBackground(Util4Eclipse
				.colorStr2ColorObj("#E6E6FA"));

		// 简单数据类型
		CTabItem item = new CTabItem(tabFolder, SWT.None | SWT.MULTI
				| SWT.V_SCROLL);
		item.setText("参与者列表");
		Composite potentialOwnerPanel = new Composite(tabFolder, SWT.NONE);
		this.createPotentialOwnerPanel(potentialOwnerPanel,1);
		item.setControl(potentialOwnerPanel);

		item = new CTabItem(tabFolder, SWT.None | SWT.MULTI | SWT.V_SCROLL);
		item.setText("抄送列表");
		Composite ccPanel = new Composite(tabFolder, SWT.NONE);
//		this.createJavaDataTypePanel(javaDataPanel);
		item.setControl(ccPanel);

		item = new CTabItem(tabFolder, SWT.None | SWT.MULTI | SWT.V_SCROLL);
		item.setText("管理者");
		Composite supervisorPanel = new Composite(tabFolder, SWT.NONE);
//		this.createXmlDataTypePanel(xmlDataPanel);
		item.setControl(supervisorPanel);

	}
	
	protected void createPotentialOwnerPanel(final Composite parent,final int flag){	


		
		GridLayout gridLayout = new GridLayout(1,true);
		parent.setLayout(gridLayout);
//		parent.setBackground(ColorConstants.white);

		//1、构造按钮
		Composite buttonPanel = getWidgetFactory().createComposite(parent);
		buttonPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		buttonPanel.setBackground(parent.getBackground());
		
		buttonPanel.setLayout(new GridLayout(3, false));

		GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalAlignment = SWT.RIGHT;

		
		Button newButton = getWidgetFactory().createButton(buttonPanel, "",
				 SWT.FLAT);
		newButton.setLayoutData(gridData);
		newButton.setToolTipText("创建新的资源定义，并绑定到当前Activity");
		newButton.setImage(newResourceImage);
		newButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				CreateResourceDefCommand command = new CreateResourceDefCommand();
				command.setShell(parent.getShell());
				command.setWorkflowProcessWrapper(processWrapper);

				activityPart.getViewer().getEditDomain().getCommandStack().execute(command);
				
				ResourceDef resourceDef = command.getResourceDef();
				if (resourceDef!=null){
					resourceBinding.addPotentialOwnerRef(resourceDef.getId());
				}
				refresh();
				activityWrapper.fireStructureChange("RESOURCE_BINDING", resourceBinding);
			}

		});
		
		Button addRefButton = new Button(buttonPanel,SWT.PUSH|SWT.FLAT);
		addRefButton.setImage(addImage);
		addRefButton.setToolTipText("绑定已存在的资源定义");
		addRefButton.addSelectionListener(new SelectionAdapter(){
			public void widgetSelected(SelectionEvent e) {
				ResourceSelectionDialog dialog = new ResourceSelectionDialog(parent.getShell(),processWrapper.getResourceListWrapper().getChildren());
				
				int result = dialog.open();
				if (result==Dialog.OK){
					ResourceDefWrapper wrapper = (ResourceDefWrapper)dialog.getSelectedResource();
					resourceBinding.addPotentialOwnerRef(wrapper.getWorkflowModelElement().getId());
					refresh();
					activityWrapper.fireStructureChange("RESOURCE_BINDING", resourceBinding);
				}
			}
			
		});


		Button deleteButton = getWidgetFactory().createButton(buttonPanel, "",
				SWT.FLAT);
		deleteButton.setImage(deleteImage);
		deleteButton.setToolTipText("删除选中的资源绑定。");
		deleteButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				ISelection selection = potentialOwnerTableViewer.getSelection();
				if(selection !=null && selection instanceof StructuredSelection){
					Object obj = ((StructuredSelection)selection).getFirstElement();
					if (flag==1){
						
						resourceBinding.getPotentialOwnerRefs().remove(obj);
						
						refresh();
						activityWrapper.fireStructureChange("RESOURCE_BINDING", resourceBinding);
					}
				}
			}
		});
		
		//2、构造参与者列表
		potentialOwnerTableViewer = new TableViewer(parent, SWT.MULTI | SWT.BORDER
				| SWT.V_SCROLL| SWT.FULL_SELECTION);
		Table table = potentialOwnerTableViewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		
		final String[] columnNames = new String[] { "参与者名称","类型" ,"值","解析器" };
		int[] columnAlignments = new int[] { SWT.LEFT,SWT.LEFT, SWT.LEFT,SWT.LEFT};
		for (int i = 0; i < columnNames.length; i++) {
			TableColumn tableColumn = new TableColumn(table,
					columnAlignments[i]);
			tableColumn.setText(columnNames[i]);

			tableColumn.setResizable(true);
			
		}
		table.setLayoutData(new GridData(GridData.FILL_BOTH));
		potentialOwnerTableViewer.setContentProvider(new ArrayContentProvider());
		potentialOwnerTableViewer.setLabelProvider( new MyTableLabelProvider());
	}
	
	public void refresh() {
		potentialOwnerTableViewer.setInput(resourceBinding.getPotentialOwnerRefs());
		
		TableColumn[] columns = potentialOwnerTableViewer.getTable().getColumns();
		for (TableColumn column : columns){
			column.pack();
		}
	}
	public void setInput(IWorkbenchPart part, ISelection selection) {
		super.setInput(part, selection);
		Object obj = ((IStructuredSelection) selection).getFirstElement();
		if(obj!=null && obj instanceof BasicActivityPart){
			activityPart = ((BasicActivityPart)obj);
			activityWrapper = (ActivityWrapper)activityPart.getModel();

			SubProcessWrapper subProcessWrapper = activityWrapper.getSubProcessWrapper();
			
			processWrapper = (WorkflowProcessWrapper)subProcessWrapper.getParent();
			
			Activity activity = (Activity)activityWrapper.getWorkflowModelElement();
			resourceBinding = activity.getResourceBinding();
			if(resourceBinding==null){
				resourceBinding = new ResourceBindingImpl();
				activity.setResourceBinding(resourceBinding);
			}
		}
	}
	
	class MyTableLabelProvider extends LabelProvider implements
			ITableLabelProvider {
		public Image getColumnImage(Object element, int index) {
			return null;
		}

		public String getColumnText(Object element, int index) {
			ResourceDef resourceDef = null;
			if (element instanceof String){
				String resourceDefId = (String) element;
				WorkflowProcess process = (WorkflowProcess) processWrapper
						.getWorkflowModelElement();
				resourceDef = (ResourceDef) process
						.getResource(resourceDefId);
			}else{
				ModelWrapper wrapper = (ModelWrapper)element;
				resourceDef = (ResourceDef)wrapper.getWorkflowModelElement();
			}

			if (resourceDef==null){
				return null;
			}

			switch (index) {
			case 0:
				return resourceDef == null ? "" : resourceDef.getDisplayName();
			case 1:
				return resourceDef == null ? "" : resourceDef.getResourceType()
						.getDisplayName();
			case 2:
				return resourceDef == null ? "" : resourceDef.getValue();
			case 3:
				return resourceDef == null ? "" : resourceDef
						.getResolverClassName() == null ? resourceDef
						.getResolverBeanName() : resourceDef
						.getResolverClassName();
			default:
				return "unknown " + index;
			}
		}
	}
	
	class ResourceSelectionDialog extends TrayDialog{
		TableViewer resourcesViewer = null;
		List<Wrapper> resourceListWrapper = null;
		Wrapper selectedWrapper = null;
		public ResourceSelectionDialog(Shell shell,List<Wrapper> resourceListWrapper){
			super(shell);
			this.resourceListWrapper = resourceListWrapper;
		}
		
		public Wrapper getSelectedResource(){
			return selectedWrapper;
		}

		protected void okPressed() {
			if (resourcesViewer!=null){
				ISelection selection = resourcesViewer.getSelection();
				if (selection!=null){
					Object obj = ((StructuredSelection)selection).getFirstElement();
					selectedWrapper = (Wrapper)obj;

				}
			}

			super.okPressed();
		}
		
		protected Control createDialogArea(Composite parent) {
			Composite container = (Composite) super.createDialogArea(parent);
			container.setLayout(new GridLayout(1, false));
			GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
			
			//2、构造参与者列表
			resourcesViewer = new TableViewer(container, SWT.MULTI | SWT.BORDER
					| SWT.V_SCROLL| SWT.FULL_SELECTION);
			Table table = resourcesViewer.getTable();
			table.setHeaderVisible(true);
			table.setLinesVisible(true);
			table.setLayoutData(gridData);
			
			final String[] columnNames = new String[] { "参与者名称","类型" ,"值","解析器" };
			int[] columnAlignments = new int[] { SWT.LEFT,SWT.LEFT, SWT.LEFT,SWT.LEFT};
			for (int i = 0; i < columnNames.length; i++) {
				TableColumn tableColumn = new TableColumn(table,
						columnAlignments[i]);
				tableColumn.setText(columnNames[i]);
				tableColumn.setResizable(true);
			}
			table.setLayoutData(new GridData(GridData.FILL_BOTH));
			resourcesViewer.setContentProvider(new ArrayContentProvider());
			resourcesViewer.setLabelProvider( new MyTableLabelProvider());
			resourcesViewer.setInput(resourceListWrapper);
			
			resourcesViewer.addSelectionChangedListener(new ISelectionChangedListener(){

				public void selectionChanged(SelectionChangedEvent event) {
					StructuredSelection selection = (StructuredSelection)event.getSelection();
					selectedWrapper = (Wrapper)selection.getFirstElement();
				}
				
			});
			resourcesViewer.addDoubleClickListener(new IDoubleClickListener(){

				public void doubleClick(DoubleClickEvent event) {
					okPressed();
					
				}
				
			});
			
			TableColumn[] columns = resourcesViewer.getTable().getColumns();
			for (TableColumn column : columns){
				column.pack();
			}
			return container;
		}
	}
}
